<template>
  <div class="build-logs">
    <div class="logs-header">
      <h3>构建日志</h3>
      <div class="logs-actions">
        <el-button
          size="small"
          @click="clearLogs"
          :disabled="logs.length === 0"
        >
          <el-icon><Delete /></el-icon>
          清空日志
        </el-button>
        <el-button
          size="small"
          @click="autoScroll = !autoScroll"
          :type="autoScroll ? 'primary' : ''"
        >
          <el-icon><VideoPlay /></el-icon>
          {{ autoScroll ? "停止自动滚动" : "自动滚动" }}
        </el-button>
      </div>
    </div>

    <div class="logs-container" ref="logsContainer">
      <div v-if="logs.length === 0" class="no-logs">
        <el-empty description="暂无日志" />
      </div>

      <div v-else class="logs-content">
        <div
          v-for="(log, index) in logs"
          :key="index"
          class="log-entry"
          :class="`log-${log.level}`"
        >
          <div class="log-timestamp">
            {{ formatTime(log.timestamp) }}
          </div>
          <div class="log-message">
            {{ log.message }}
          </div>
          <div v-if="log.data" class="log-data">
            <el-button size="small" @click="toggleData(index)">
              {{ expandedData.has(index) ? "隐藏详情" : "显示详情" }}
            </el-button>
            <div v-if="expandedData.has(index)" class="log-data-content">
              <pre>{{ JSON.stringify(log.data, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, watch } from "vue";
import { io } from "socket.io-client";
import { API_CONFIG } from "../utils/constants.js";

export default {
  name: "BuildLogs",
  props: {
    projectId: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const logs = ref([]);
    const autoScroll = ref(true);
    const logsContainer = ref(null);
    const expandedData = ref(new Set());
    const socket = ref(null);

    // 格式化时间
    const formatTime = (timestamp) => {
      const date = new Date(timestamp);
      return date.toLocaleTimeString();
    };

    // 切换数据展开状态
    const toggleData = (index) => {
      if (expandedData.value.has(index)) {
        expandedData.value.delete(index);
      } else {
        expandedData.value.add(index);
      }
    };

    // 清空日志
    const clearLogs = () => {
      logs.value = [];
      expandedData.value.clear();
    };

    // 滚动到底部
    const scrollToBottom = () => {
      if (autoScroll.value && logsContainer.value) {
        nextTick(() => {
          logsContainer.value.scrollTop = logsContainer.value.scrollHeight;
        });
      }
    };

    // 监听日志变化，自动滚动
    watch(
      logs,
      () => {
        scrollToBottom();
      },
      { deep: true },
    );

    // 连接WebSocket
    const connectSocket = () => {
      socket.value = io(API_CONFIG.WEBSOCKET_URL);

      socket.value.on("connect", () => {
        console.log("🔌 WebSocket连接成功");
        socket.value.emit("join-build-session", props.projectId);
      });

      socket.value.on("build-log", (logEntry) => {
        logs.value.push(logEntry);
      });

      socket.value.on("disconnect", () => {
        console.log("🔌 WebSocket连接断开");
      });
    };

    // 加载历史日志
    const loadHistoryLogs = async () => {
      try {
        const response = await fetch(`/api/build/logs/${props.projectId}`);
        const data = await response.json();
        if (data.success) {
          logs.value = data.logs;
        }
      } catch (error) {
        console.error("加载历史日志失败:", error);
      }
    };

    onMounted(() => {
      connectSocket();
      loadHistoryLogs();
    });

    onUnmounted(() => {
      if (socket.value) {
        socket.value.emit("leave-build-session", props.projectId);
        socket.value.disconnect();
      }
    });

    return {
      logs,
      autoScroll,
      logsContainer,
      expandedData,
      formatTime,
      toggleData,
      clearLogs,
    };
  },
};
</script>

<style scoped>
.build-logs {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.logs-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.logs-actions {
  display: flex;
  gap: 8px;
}

.logs-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.no-logs {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logs-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #1e1e1e;
  color: #ffffff;
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  font-size: 13px;
  line-height: 1.5;
}

.log-entry {
  margin-bottom: 8px;
  padding: 8px;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.05);
}

.log-timestamp {
  color: #888;
  font-size: 11px;
  margin-bottom: 4px;
}

.log-message {
  color: #ffffff;
  word-break: break-word;
}

.log-data {
  margin-top: 8px;
}

.log-data-content {
  margin-top: 8px;
  padding: 8px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
}

.log-data-content pre {
  margin: 0;
  color: #e6e6e6;
  font-size: 11px;
  overflow-x: auto;
}

/* 日志级别样式 */
.log-info {
  border-left: 3px solid #409eff;
}

.log-success {
  border-left: 3px solid #67c23a;
}

.log-warning {
  border-left: 3px solid #e6a23c;
}

.log-error {
  border-left: 3px solid #f56c6c;
}

.log-docker {
  border-left: 3px solid #00d4aa;
}

.log-dependency {
  border-left: 3px solid #ff9f43;
}

.log-package {
  border-left: 3px solid #5f27cd;
}
</style>
